<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="任务主题" prop="taskTheme">
        <el-input
          v-model="queryParams.taskTheme"
          placeholder="请输入任务主题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="taskType">
        <el-select
          v-model="queryParams.taskType"
          placeholder="请选择任务类型"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in taskPublishType"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务开始时间" label-width="150px">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="开始日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="任务完成时间" label-width="150px">
        <el-date-picker
          v-model="dateRange1"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="完成日期"
          end-placeholder="完成日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="viewList" @selection-change="handleSelectionChange" stripe>
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="任务主题" align="center" prop="taskTheme" />
      <el-table-column label="任务类型" align="center" prop="taskType" :formatter="typeFormat" />
      <el-table-column label="任务周期" align="center" prop="startDate,endDate" ><template slot-scope="scope">{{scope.row.startDate}}至{{scope.row.endDate}}</template></el-table-column>
    <!--  <el-table-column label="发起部门" align="center" prop="department" /> -->
      <!-- <el-table-column label="发起人" align="center" prop="taskPublishUserName" /> -->
       <el-table-column label="任务对象" align="center" prop="stationName" />
       <el-table-column label="任务状态" align="center" prop="taskStatus" :formatter="statusFormat" />
<!--       <el-table-column label="执行人" align="center" prop="taskMainInformation" />-->
       <el-table-column label="执行部门" align="center" prop="exedept" />
       <el-table-column label="完成时间" align="center" prop="completionTime" />

       <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
           <template slot-scope="scope">

             <el-button
               size="mini"
               type="text"
               icon="el-icon-view"
               v-if="handleAcceptShow(scope.row) == 1"
               @click="handleAllotAction(scope.row)"
             >分配</el-button>
             <el-button
               size="mini"
               type="text"
               icon="el-icon-view"
               v-if="handleAcceptShow(scope.row) == 2"
               @click="handleAcceptAction(scope.row)"
             >领取</el-button>
             <el-button
               size="mini"
               type="text"
               icon="el-icon-view"
               v-if="handleAcceptShow(scope.row)== 3"
               :disabled="true"
             >已分配</el-button>

               <el-button
                 size="mini"
                 type="text"
                 icon="el-icon-view"
                 @click="handleCheck(scope.row)"
               >{{handleDetailButtonShow(scope.row) == 0?'检查':'详情'}}</el-button>
           </template>
       </el-table-column>
     </el-table>

     <pagination
       v-show="total>0"
       :total="total"
       :page.sync="queryParams.pageNum"
       :limit.sync="queryParams.pageSize"
       @pagination="getList"
     />

     <!-- 添加或修改任务详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-table v-loading="peopleLoading" ref = "multipleTable" :data="peopleDictionary" @select-all="onSelectAll" @selection-change="onSelectItem" @row-click="onSelectOp">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="执行人员" align="center" prop="userName"/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listView, getView, delView, addView, updateView, exportView ,acceptTaskAction,allotTaskAction} from "@/api/task/view";
import { getUserId,userPost,getDeptUserList} from "@/api/task/information";


export default {
  name: "View",
  data() {
    return {
      // 遮罩层
      loading: true,
      peopleLoading: true,
      //部门人员
      peopleDictionary:[],
        multipleSelection:[],
        rowTaskViewId:undefined,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 任务详情表格数据
      viewList: [],
      // 启用状态字典
      taskTemplateUseStatus: [],
      // 任务类型字典
      taskPublishType: [],
      // 检查模板表格数据
      taskList: [],
      contentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //当前用户userId
      memberUserId: undefined,
      //当前人员的岗位 director -处长 section_chief -科长 section_member -科员
      userPost: "0",
      //展示详情或者检查 0-检查 1-详情
      showDetailFlag:1,
      //展示分配或者领取 0-不展示 1-分配 2-领取 3-已分配
      showAcceptFlag:0,

      dateRange: [],
      dateRange1: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: undefined,
        taskFormId: undefined,
        stationId: undefined,
        status: undefined,
        checkUserId: undefined,
        handleDescription: undefined,
        createId: undefined,
        updateId: undefined,
        taskTheme: undefined,
        taskType: undefined,
        startDate: undefined,
        completionTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateTheme: [
          { required: true, message: "模板主题不能为空", trigger: "blur" }
        ],
        templateType: [
          { required: true, message: "模板类型（1-双随机任务;2-周期任务;3-特定任务）不能为空", trigger: "blur" }
        ],
      }
    };
  },

  created() {
    this.getList();
      this.receiveUserId();
      this.getUserPost();
    this.getDicts("task_publish_type").then(response => {
      this.taskPublishType = response.data;
    });
    this.getDicts("task_publish_status").then(response => {
      this.taskTemplateUseStatus = response.data;
    });
  },
    mounted(){
        this.getNextList()
    },


  methods: {

      async getNextList(){
          console.log(this.$route);
          let taskId = this.$route.query.taskId;
          if(taskId !=null && taskId !=undefined){
              this.queryParams.taskId = taskId;
              this.getList();
          }
      },

    onSelectAll(){
        this.$refs.multipleTable.clearSelection();
    },

    onSelectItem(rows){
        if (rows.length > 1) {
            var newRows = rows.filter((it, index) => {
                if (index == rows.length - 1) {
                    this.$refs.multipleTable.toggleRowSelection(it, true);
                    return true;
                } else {
                    this.$refs.multipleTable.toggleRowSelection(it, false);
                    return false;
                }
            });
            this.multipleSelection = newRows;
        } else {
            this.multipleSelection = rows;
        }
    },

    onSelectOp(row) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row, true);
        this.multipleSelection = [];
        this.multipleSelection.push(row);
    },

    /** 查询任务详情列表 */
    getList() {
      this.loading = true;
      listView(this.addDateRange2(this.queryParams, this.dateRange, this.dateRange1)).then(response => {
        this.viewList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取用户userId
    receiveUserId(){
        getUserId().then(response => {
            this.memberUserId = response.data;
        });
    },
    /** 查询当前人员的岗位*/
    getUserPost() {
        userPost().then(response => {
            this.userPost = response.data;
            console.log(this.userPost);
        });
    },
    //对展示的按钮进行判断
    handleDetailButtonShow(row){
        let showDetailFlag = 1;
        if(this.userPost == 'director'){
            showDetailFlag = 1;
        }else if(this.userPost !='director'){
            if((this.memberUserId == row.checkUserId) && (row.taskStatus != '3' && row.taskStatus !='4')){
                showDetailFlag = 0;
            }
        }else{
            showDetailFlag = 1;
        }
        return showDetailFlag;
    },
    //对于分配按钮进行判断
    handleAcceptShow(row){
        let showAcceptFlag = 0;
      if(this.userPost == 'director'){
          showAcceptFlag = 0;
      }else if(this.userPost == 'section_chief'){
          if(!row.checkUserId || row.checkUserId ==''){
              showAcceptFlag = 1;
          }else{
              showAcceptFlag = 3;
          }
      }else if(this.userPost == 'section_member'){
          if(!row.checkUserId || row.checkUserId ==''){
              showAcceptFlag = 2;
          }else{
              showAcceptFlag = 3;
          }
      }else{
          showAcceptFlag = 0;
      }
      return showAcceptFlag;
    },
    //科长点击分配
    handleAllotAction(row){
        this.peopleLoading = true;
        this.open = true;
        this.title = "分配人员";
        this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection();
        });
        this.rowTaskViewId = row.id;
        getDeptUserList().then(response => {
            this.peopleDictionary = response.data;
            this.peopleLoading = false;
        });


    },
      //查询当前部门下的人员
      getPeopleList() {
          getDeptUserList().then(response => {
              this.peopleDictionary = response.data;
          });
      },
    //科员点击领取
    handleAcceptAction(row){
        let taskViewId = row.id;
        this.$confirm('是否确认领取该任务?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        }).then(function() {
            return acceptTaskAction(taskViewId);
        }).then(() => {
            this.getList();
            this.msgSuccess("任务领取成功");
        }).catch(function() {});
    },
      handleDelete(row) {
          const ids = row.id || this.ids;
          this.$confirm('是否确认删除责任告知书的数据项?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          }).then(function() {
              return delResponsibilityNotice(ids);
          }).then(() => {
              this.getList();
              this.msgSuccess("删除成功");
          }).catch(function() {});
      },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.taskTemplateUseStatus, row.taskStatus);
    },
    // 类型典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.taskPublishType, row.taskType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.multipleTable.clearSelection();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        taskId: undefined,
        taskFormId: undefined,
        stationId: undefined,
        status: "0",
        checkUserId: undefined,
        handleDescription: undefined,
        delFlag: undefined,
        createTime: undefined,
        createId: undefined,
        updateTime: undefined,
        updateId: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      // 默认日期赋值
      this.dateRange = [];
      this.dateRange1 = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务详情";
    },
    /** 修改按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getView(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "任务详情";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
        let taskViewId = this.rowTaskViewId;
        if(!this.multipleSelection[0] ||this.multipleSelection[0] == ''){
            this.msgError("请选择一位人员后，再进行提交操作！");
            return ;
        }
        let userId = this.multipleSelection[0].userId;

        this.$confirm('是否确认分配该任务?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        }).then(function() {
            return allotTaskAction(taskViewId,userId);
        }).then(() => {
            this.getList();
            this.msgSuccess("任务分配成功");
            this.open = false;
        }).catch(function() {});



        /*    updateView(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });*/
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除任务详情编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delView(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
      //点击检查跳转
      handleCheck(row){
          this.reset();
          const taskViewId = row.id
          this.$router.push({
              path:"/taskk/check",
              query:{
                  taskViewId:taskViewId
              }
          })
          console.log(this.$router);
      },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有任务详情数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportView(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
